const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");


router.post('/deliver/getCargoByCarId', async ctx => {
    let tenantId = ctx.user.tenantId;
    let body = ctx.request.body;
    let carId = body.carId ? body.carId : 0;
    let billId = body.billId ? body.billId : 0; // 如果是扫描销售单ID
    if (billId) {
        let sql = `select top 1 cargoId from cargo_invoice where tenantId=${tenantId} and iid=${billId} `
        let car = await db.query(sql, {type: QueryTypes.SELECT, plain: true})
        if(!car) return ctx.err('该单据未有装车记录')

        let cargo = await db.models['cargo'].findOne({
            where: {
                id: car.cargoId
            }
        })
        if(tool.xe.toNumber(cargo.state) === 2) {
            return ctx.err('票据已确认收货')
        }
        let cargoIds = [cargo.id];
        let list = [cargo]

        if (cargoIds.length === 0) {
            return ctx.err('没有待配送单据');
        }
        let list1 = await tool.unDeliver(cargoIds.join(','));
        if (list1.length === 0) {
            return ctx.suc('没有待配送单据');
        }
        let ret = []
        for (let i = 0; i < list.length; i++) {
            let list2 = [];
            list1.map(it => {
                if (list[i].id === it.cargoId) {
                    list2.push(it);
                }
            })
            let row = list[i].toJSON()
            row.cargo = list2;
            ret.push(row)
        }
        return ctx.suc('', ret);
    }
    else {
        let type = body.type;
        let state = 1;
        if (type === 'delivered') {
            state = 2;
        }
        let sql = `select * from cargo where tenantId=${tenantId} and state = ${state} and carsId=${carId}`
        if (state === 2) {
            sql += ' order by id desc '
        }
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        let cargoIds = [];
        list.map(cargo => {
            cargoIds.push(cargo.id);
        })
        if (cargoIds.length === 0) {
            return ctx.suc("没有待配送单据");
        }
        let list1 = await tool.unDeliver(cargoIds.join(','));
        list.map(cargo => {
            let list2 = []
            list1.map(it => {
                if (cargo.id === it.cargoId) {
                    list2.push(it);
                }
            })
            cargo.cargo = list2
        })
        return ctx.suc('', list);
    }
})

module.exports = router;
